<template>
	<view class="webview-page">
		<!-- 顶部导航栏 -->
		<view class="top-nav">
			<view class="nav-left" @click="handleBack">
				<i class="fa fa-arrow-left"></i>
			</view>
			<view class="nav-title">{{ title }}</view>
			<view class="nav-right" @click="handleRefresh">
				<i class="fa fa-refresh"></i>
			</view>
		</view>

		<!-- web-view 组件 -->
		<web-view :src="url" @message="handleMessage" @load="handleLoad" @error="handleError"></web-view>

		<!-- 加载中提示 -->
		<u-loading-page v-if="loading"></u-loading-page>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 网页标题
				title: '网页视图',

				// 网页URL
				url: '',

				// 加载状态
				loading: true
			};
		},

		onLoad(options) {
			// 获取传递的URL参数
			if (options.url) {
				this.url = decodeURIComponent(options.url);
			}

			// 获取传递的标题参数
			if (options.title) {
				this.title = decodeURIComponent(options.title);
			}
		},

		methods: {
			// 处理返回按钮点击
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 处理刷新按钮点击
			handleRefresh() {
				this.loading = true;

				// 重新加载网页
				const webView = this.$mp.page.$getAppWebview().children()[0];
				webView.reload();
			},

			// 处理网页加载完成
			handleLoad() {
				this.loading = false;
			},

			// 处理网页加载错误
			handleError() {
				this.loading = false;

				uni.showToast({
					title: '网页加载加载失败',
					icon: 'none',
					duration: 2000
				});
			},

			// 处理网页发送的消息
			handleMessage(event) {
				console.log('收到网页消息:', event.detail.data);

				// 可以在这里这里处理网页发送过来的消息
				// 例如：关闭当前页面、跳转到其他页面等
				const data = event.detail.data[0];
				if (data.action === 'close') {
					this.handleBack();
				} else if (data.action === 'navigate') {
					uni.navigateTo({
						url: data.url
					});
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 页面视图页面 */
	.webview-page {
		width: 100%;
		height: 100%;
	}

	/* 顶部导航栏 */
	.top-nav {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 100rpx;
		background-color: #4188EF;
		color: white;
		padding: 0 30rpx;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;

		.nav-left,
		.nav-right {
			width: 60rpx;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			i {
				font-size: 36rpx;
			}
		}

		.nav-title {
			font-size: 36rpx;
			font-weight: 500;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			max-width: 500rpx;
		}
	}

	/* web-view 组件 */
	web-view {
		width: 100%;
		height: calc(100vh - 100rpx);
		margin-top: 100rpx;
	}
</style>